<?php

namespace App\Http\Controllers\Admin\Product;

use App\Http\Controllers\Controller;
use App\Models\Category\Category;
use App\Models\Product;
use App\Models\ProductReply;
use App\Traits\Controllers\DestroyTraits;
use App\Traits\Controllers\UpdateTraits;
use App\Transformers\Product\ProductReplyTransformer;
use Carbon\Carbon;
use ElfSundae\Laravel\Hashid\Facades\Hashid;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;

class ProductReplyController extends Controller
{

    use DestroyTraits;

    public $model = ProductReply::class;

    public $transformer = ProductReplyTransformer::class;

    /**
     * 商品评论列表
     */
    public function index(Request $request)
    {

        //先处理传过来的搜索数据
        $this->formatIndexQuery($request);

        $product_name = $request->input('product_name');
        $request->offsetUnset('product_name');

        $start_time = $request->input('start_time');
        $end_time = $request->input('end_time');

        //获取传过来的时间类型
        $time = $request->input('time');


        $data = $this
            ->getQuery()
            ->pimp()//自动转换where条件
            ->when($time || ($start_time && $end_time), function ($query) use ($time,$start_time,$end_time) {
                //自定义时间
                if(!empty($start_time) && !empty($end_time)){
                    $query->whereBetween('created_at',[$start_time,$end_time]);
                }

                //搜索今天数据
                if ($time == "today") {
                    $query->whereBetween('created_at', [Carbon::now()->startOfDay(), Carbon::now()->endOfDay()]);
                }

                //搜索昨天数据
                if ($time == "yesterday") {
                    $query->whereDay('created_at', [Carbon::now()->yesterday(), Carbon::now()->startOfDay()]);
                }

                //搜索最近一周数据
                if ($time == "week") {
                    $query->whereBetween('created_at', [Carbon::now()->subDays(7), Carbon::now()->subDays(0)]);
                }

                //搜索最近三十天数据
                if ($time == "thirty") {
                    $query->whereBetween('created_at', [Carbon::now()->subDays(30), Carbon::now()->subDays(0)]);
                }

                //搜索本月数据
                if ($time == "month") {
                    $query->whereBetween('created_at', [Carbon::now()->startOfMonth(), Carbon::now()->endOfMonth()]);
                }

                //搜索本年数据
                if ($time == "year") {
                    $query->whereBetween('created_at', [Carbon::now()->startOfYear(), Carbon::now()->endOfYear()]);
                }
            })
            ->when($product_name,function ($q) use ($product_name){
                $q->whereHas('product',function ($q) use ($product_name){
                    $q->where('product_name','like',$product_name);
                });
            })
            ->paginate($this->getPageLimit());

        return $this->response->paginator($data, resolve($this->transformer));
    }

    /**
     * 商品评论回复
     */
    public function update($id, Request $request)
    {
        //验证用户凭证信息
        $this->validateData($request);

        $data = $this->getQuery()->findOrFail($id);

        if ($this->policy) {
            $this->authorize('update', $data);
        }
        $request->offsetSet('merchant_reply_time',date('Y-m-d H:i:s',time()));
        $request->offsetSet('is_reply',1);

        $data->fill($request->all());
        $data->save();

        return $this->response->noContent();
    }




    /**
     * 前台 添加评论
     */
    public function store(Request $request) //TODO 写前台的时候再说，别忘了
    {
        $this->validateData($request);

        /**
         * 保存用户
         */
        $user_id = $this->web_user('id');
        $request->offsetSet('user_id', $user_id);
        $request->offsetSet('nickname', $this->web_user('nickname'));
        $request->offsetSet('avatar', $this->web_user('avatar'));

        /**
         * 生成唯一id unique
         */
        //获取订单id和商品id
        $order_id = $request->input('order_id');
        $product_id = $request->input('product_id');
        $unique = Hashid::encode($order_id.$product_id.$user_id);
        $request->offsetSet('unique',$unique);

        //判断评论表中unique是否存在
        $uniqued = $this->getQuery()->where('user_id',$this->web_user('id'))->pluck('unique');

        if ($uniqued == $unique){
            return $this->response->error(500,'不能重复评论');
        }

        $model = $this->getQuery()->fill($request->all());
        $model->save();

        return $this->response->created();
    }


    /**
     * 参数验证规则
     *
     * @param Request $request
     * @return array
     */
    public function rules(Request $request): array
    {
        switch ($request->method()) {
            case 'GET':
                return [];
                break;
            case 'POST':
                return [
                    'order_id' => 'bail|required',
                    'product_id' => 'bail|required',
                    'comment' => 'bail|required',
                    'pics' => 'bail|nullable|array',
                    'product_score' => 'bail|required',
                    'service_score' => 'bail|required',
                ];
                break;
            case 'PATCH':
            case 'PUT':
            return [
                'merchant_reply_content' => 'bail|required'
            ];
            break;
        }
        return [];
    }

    /**
     * 验证信息
     *
     * @return array
     */
    public function ruleMessages(): array
    {
        return [
            'order_id.required' => '订单id 不能为空',
            'product_id.required' => '商品 不能为空',
            'comment.required' => '评论内容 不能为空',
            'pics.array' => '评论图片 格式不正确',
            'product_score.required' => '商品分数 不能为空',
            'service_score.required' => '服务分数 不能为空',
            'merchant_reply_content.required' => '回复内容 不能为空',
        ];
    }
}



